package com.common.base.utils

import android.app.Activity
import android.content.Context
import android.os.Build
import android.provider.Settings
import android.text.TextUtils
import android.util.DisplayMetrics
import android.view.View
import android.view.Window
import android.view.WindowManager

object NavigationUtil {
    /**
     * 获取 虚拟按键的高度
     * @param context
     * @return
     */
    @JvmStatic
    fun getNegativeHeight(context: Context): Int {
        val totalHeight = getDpi(context)

        val contentHeight = getScreenHeight(context)
        return totalHeight - contentHeight
    }

    //获取屏幕原始尺寸高度，包括虚拟功能键高度
    @JvmStatic
    fun getDpi(context: Context): Int {
        var dpi = 0
        val windowManager = context.getSystemService(Context.WINDOW_SERVICE) as WindowManager
        val display = windowManager.defaultDisplay
        val displayMetrics = DisplayMetrics()
        val c: Class<*>
        try {
            c = Class.forName("android.view.Display")
            val method = c.getMethod("getRealMetrics", DisplayMetrics::class.java)
            method.invoke(display, displayMetrics)
            dpi = displayMetrics.heightPixels
        } catch (e: Exception) {
            e.printStackTrace()
        }

        return dpi
    }

    /**
     * 获得屏幕高度
     *
     * @param context
     * @return
     */
    @JvmStatic
    fun getScreenHeight(context: Context): Int {
        val wm = context
                .getSystemService(Context.WINDOW_SERVICE) as WindowManager
        val outMetrics = DisplayMetrics()
        wm.defaultDisplay.getMetrics(outMetrics)
        return outMetrics.heightPixels
    }

    /**
     * 获取虚拟按键的高度
     *      1. 全面屏下
     *          1.1 开启全面屏开关-返回0
     *          1.2 关闭全面屏开关-执行非全面屏下处理方式
     *      2. 非全面屏下
     *          2.1 没有虚拟键-返回0
     *          2.1 虚拟键隐藏-返回0
     *          2.2 虚拟键存在且未隐藏-返回虚拟键实际高度
     */
    @JvmStatic
    public fun getNavigationBarHeightIfRoom(context: Context?): Int {
        if(navigationGestureEnabled(context)){
            return 0
        }
        return getCurrentNavigationBarHeight(context as Activity)
    }

    /**
     * 全面屏（是否开启全面屏开关 0 关闭  1 开启）
     *
     * @param context
     * @return
     */
    @JvmStatic
    public fun navigationGestureEnabled(context: Context?): Boolean{
        val index = Settings.Global.getInt(context?.contentResolver, getDeviceInfo(), 0)
        return index != 0
    }

    /**
     * 获取设备信息（目前支持几大主流的全面屏手机，亲测华为、小米、oppo、魅族、vivo都可以）
     *
     * @return
     */
    @JvmStatic
    fun getDeviceInfo(): String {
        val brand = Build.BRAND

        if(TextUtils.isEmpty(brand))
            return "navigationbar_is_min"

        if (brand.equals("HUAWEI", true)) {
            return "navigationbar_is_min"
        } else if (brand.equals("XIAOMI", true)) {
            return "force_fsg_nav_bar"
        } else if (brand.equals("VIVO", true)) {
            return "navigation_gesture_on"
        } else if (brand.equals("OPPO", true)) {
            return "navigation_gesture_on"
        } else {
            return "navigationbar_is_min"
        }
    }

    /**
     * 非全面屏下 虚拟键实际高度(隐藏后高度为0)
     * @param activity
     * @return
     */
    @JvmStatic
    public fun getCurrentNavigationBarHeight(activity: Activity): Int{
        if(isNavigationBarShown(activity)){
            return getNavigationBarHeight(activity)
        } else{
            return 0
        }
    }

    /**
     * 非全面屏下 虚拟按键是否打开
     * @param activity
     * @return
     */
    @JvmStatic
    public fun isNavigationBarShown(activity: Activity?): Boolean{
        //虚拟键的view,为空或者不可见时是隐藏状态
        val view  = activity?.findViewById<View>(android.R.id.navigationBarBackground)?: null
        if(view == null){
            return false
        }
        val visible = view.getVisibility()
        if(visible == View.GONE || visible == View.INVISIBLE){
            return false
        }else{
            return true
        }
    }

    /**
     * 非全面屏下 虚拟键高度(无论是否隐藏)
     * @param context
     * @return
     */
    @JvmStatic
    public fun getNavigationBarHeight(context: Context): Int{
        var result = 0
        val resourceId = context.getResources().getIdentifier("navigation_bar_height","dimen", "android")
        if (resourceId > 0) {
            result = context.getResources().getDimensionPixelSize(resourceId)
        }
        return result
    }

    /**
     * 隐藏虚拟栏 ，显示的时候再隐藏掉
     * @param window
     */
    fun hideNavigationBar(window: Window?) {
        window?.apply {
            decorView.systemUiVisibility = View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
            decorView.setOnSystemUiVisibilityChangeListener {
                var uiOptions = View.SYSTEM_UI_FLAG_LAYOUT_STABLE or  //布局位于状态栏下方
                        View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION or  //全屏
                        View.SYSTEM_UI_FLAG_FULLSCREEN or  //隐藏导航栏
                        View.SYSTEM_UI_FLAG_HIDE_NAVIGATION or
                        View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                uiOptions = if (Build.VERSION.SDK_INT >= 19) {
                    uiOptions or View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY
                } else {
                    uiOptions or View.SYSTEM_UI_FLAG_LOW_PROFILE
                }
                decorView.systemUiVisibility=uiOptions
            }

//            if (Build.VERSION.SDK_INT >= 21) {
//                clearFlags(67108864)
//                clearFlags(134217728)
//                decorView.systemUiVisibility = 1280
//                addFlags(Int.MIN_VALUE)
//                statusBarColor = 0
//            } else if (Build.VERSION.SDK_INT >= 19) {
//                addFlags(67108864)
//            }
//
//            // 设置窗口的布局参数
//            val params = window.attributes
//            // 设置NavigationBar为透明
//            params.systemUiVisibility = (View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
//                    or View.SYSTEM_UI_FLAG_LAYOUT_STABLE
//                    or View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN)
//            window.attributes = params
        }
    }

}